﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using ZK.Common;

namespace ZK.HardWareBLL
{
    /// <summary>
    /// 泥人网络继电器
    /// </summary>
    public class NRNetRelayBLL
    {
        Models.TerminalM haredWareCommonM;
        Socket client;

        public NRNetRelayBLL(Models.TerminalM terminalM)
        {
            haredWareCommonM = terminalM;
        }
        #region 打开某个输出口
        //stach begin 1 2 3 4 5 6 ..................
        /// <summary>
        /// 打开某个输出口
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public bool HandleStach(int num=1)
        {
            try
            {
                ///创建客户端
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ///IP地址
                IPAddress ip = IPAddress.Parse(haredWareCommonM.ip);
                ///端口号
                IPEndPoint endPoint = new IPEndPoint(ip, (int)haredWareCommonM.port);
                ///建立与服务器的远程连接
                client.Connect(endPoint);
                ///线程问题
                //Thread thread = new Thread(ReciveMsg);
                //thread.IsBackground = true;
                //thread.Start(client);
                //将字符串指令转换为byte数组
                byte[] buf = System.Text.Encoding.Default.GetBytes("AT+STACH" + num + "=1,1\r\n");
                //发送AT指令
                client.Send(buf);

                byte[] recbuf = new byte[10];//真正使用时，接收缓冲区需要适当的调整
                                             //等待硬件响应命令，接收到的数据为byte数组
                                             //会等待到有数据返回为止
                int recLen = client.Receive(recbuf);
                client.Close();
                //将byte数组转为字符串
                string str = System.Text.Encoding.Default.GetString(recbuf);
                str = str.Replace("\r\n", "").Trim().ToLower();
                if (!str.Contains("ok"))
                {
                    Common.Log4.LogManage.WriteErr(str);
                    Common.DelegateHelper.InfoMessageEvent?.Invoke(str);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr(ex.ToString());
                Common.DelegateHelper.InfoMessageEvent?.Invoke(ex.Message);
                return false;
            }

        }
        #endregion

        #region 获取输入节点有无遮挡
        /// <summary>
        /// 获取输入节点有无遮挡
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public int getIn(int num =0)
        {
            int res = 0;
            string srear = SearchStateIn(num);
            if (!string.IsNullOrEmpty(srear))
            {
                if (num > 0)
                {
                    if (srear.Split(':')[1] == "1")
                    {
                        return num;
                    }
                }
                else
                {
                    string[] s = srear.Replace("OCCH", "").Split('+');
                    string aaa = string.Empty;
                    foreach (string item in s)
                    {
                        if (!string.IsNullOrEmpty(item) && item.Split(':')[1] == "1")
                        {
                           return Convert.ToInt32(item.Split(':')[0]);
                        }
                    }
                }
            }
            return res;

        }
        #endregion

        #region 获取对应输入的结果
        /// <summary>
        /// 获取对应输入的结果
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public string SearchStateIn(int num = 0)
        {
            try
            {
                ///创建客户端
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ///IP地址
                IPAddress ip = IPAddress.Parse(haredWareCommonM.ip);
                ///端口号
                IPEndPoint endPoint = new IPEndPoint(ip, (int)haredWareCommonM.port);
                ///建立与服务器的远程连接
                client.Connect(endPoint);
                ///线程问题
                //Thread thread = new Thread(ReciveMsg);
                //thread.IsBackground = true;
                //thread.Start(client);
                //将字符串指令转换为byte数组
                // byte[] buf = new byte[]{ 0x41, 0x54 ,0x2B, 0x4F, 0x43 ,0x43 ,0x48, 0x30, 0x3D, 0x3F ,0x0D, 0x0A };
                //string aaa = System.Text.Encoding.Default.GetString(buf);
                //string sendSre = "AT+OCCH0=?\r\n";
                 byte[] buf = System.Text.Encoding.Default.GetBytes("AT+OCCH"+num+"=?\r\n");
               // byte[] buf = new byte[] { 0x41, 0x54, 0x2B, 0x4F, 0x43, 0x43, 0x48, 0x30, 0x3D, 0x3F, 0x0D, 0x0A };
                Common.ShowBlackBox.WriteLine("2 "+ string.Join("-",buf));
                //发送AT指令
                client.Send(buf);
                int leng = 10;
                if (num ==0)
                {
                    leng = 40;
                }
                byte[] recbuf = new byte[leng];//真正使用时，接收缓冲区需要适当的调整
                                               //等待硬件响应命令，接收到的数据为byte数组
                                               //会等待到有数据返回为止
                List<byte> bys = new List<byte>();
                while (bys.Count < leng)
                {
                   int temp =  client.Receive(recbuf);
                    bys.AddRange(recbuf.Take(temp));
                }
                Common.ShowBlackBox.WriteLine("2 缓存数据个数： " + bys.Count);
                // client.Receive(recbuf);
                //Common.ShowBlackBox.WriteLine("2 缓存数据个数： " + recLen);
                string str = System.Text.Encoding.Default.GetString(bys.ToArray());
               
                client.Close();
                //将byte数组转为字符串
                str = str.Replace("\r\n", "").Trim();
                Common.ShowBlackBox.WriteLine("1 " + str);

                return str;
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr(ex.ToString());
                Common.ShowBlackBox.WriteLine("3 " + ex.ToString());
                return "";
            }

        }
        #endregion

        /// <summary>
        /// 字符串转16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
    }
}
